from random import randrange

from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity, verify_jwt_in_request, create_access_token
from tencentcloud.common.exception import TencentCloudSDKException

from api.article2api import article_api
from api.user2api import user_api
from api.word2api import word_api
from models import User, get_redis_connection, db
from utils.random_Name import getname
from utils.send_SMS import is_valid_china_mobile, sendSMS

api = Blueprint('api', __name__)

api.register_blueprint(user_api, url_prefix='/user')
api.register_blueprint(word_api, url_prefix='/word')
api.register_blueprint(article_api, url_prefix='/article')


@api.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        return jsonify({'status': 'api is ok'})
    else:
        return 'Please use "POST" method to access this website'


@api.route('/verify_code', methods=['GET'])
def get_code():
    phone_number = request.args['phone_number']
    redis_client = get_redis_connection()
    exist = redis_client.exists(f'verify_code:{phone_number}')
    if exist:
        return jsonify({'status': 'Too Many Times Request'}), 401
    else:
        if is_valid_china_mobile(phone_number):
            try:
                code = randrange(1000, 9999)
                sendSMS(phone_number, code, '1')
                redis_client.set(f'verify_code:{phone_number}', code, 60)
                return jsonify({'status': 'success', 'code': 200})
            except TencentCloudSDKException as err:
                return jsonify({'error': err, 'code': 401})
        else:
            return jsonify({'error': 'incorrect phone number', 'code': 401})


@api.route('/login', methods=['POST'])
def login():
    data = request.get_json()
    phone = data.get('phone_number')
    code = data.get('code')

    if not is_valid_china_mobile(phone):
        return jsonify({'error': 'incorrect phone number', 'code': 401})
    redis_client = get_redis_connection()
    redis_code = redis_client.get(f'verify_code:{phone}')
    if redis_code:
        if str(redis_code).strip() != str(code).strip():
            return jsonify({'error': '验证码错误', 'code': 401})
        user = User.query.filter_by(phone=phone).first()
        if user:
            access_token = create_access_token(identity=user.id)
        else:
            user = User(phone=phone, username='小芝麻_%s' % (getname(5)))
            db.session.add(user)
            db.session.commit()
            access_token = create_access_token(identity=user.id)
        return jsonify(status='success', access_token=access_token), 200
    return jsonify({'error': '验证码已过期或失效', 'code': 401})
